package com.example.demo.conf;

import com.example.demo.exception.Asserts;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class HeaderFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();
        System.out.println(requestURI);
        if ("/admin/test1".equals(requestURI)) {
            String checkHeader = httpRequest.getHeader("check");
            if (!"caomei".equals(checkHeader)) {
                httpResponse.setStatus(505);
                httpResponse.getWriter().write("请求头校验异常错误");
                Asserts.fail("请求头校验异常错误");
            }
        }
        chain.doFilter(request, response);
    }
}
